package com.ljm.config;



import com.ljm.filter.TokenAuthenticationFilter;
import com.ljm.filter.TokenLoginFilter;
import com.ljm.pojo.DefaultPasswordEncoder;
import com.ljm.security.TokenLogoutHandler;
import com.ljm.security.TokenManager;
import com.ljm.security.UnauthorizedEntryPoint;
import com.ljm.securitys.JwtAccessDeniedHandler;
import com.ljm.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * <p>
 * Security配置类
 * </p>
 *
 * @author qy
 * @since 2019-11-18
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
    //  查询到用户权限
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    //  token   返回   用户名  + 角色  +  密码  加密  jwt  字符串
    @Autowired
    private TokenManager tokenManager;
    /// 登录信息  登录过来的密码MD5 加密
    @Qualifier("DefaultPasswordEncoder")
    @Autowired
    private DefaultPasswordEncoder defaultPasswordEncoder;
    //   定义返回的 redis 模板
    @Qualifier("redisTemplateAAA")
    @Autowired
    private RedisTemplate redisTemplate;

    ///   未授权 处理
    @Autowired
    UnauthorizedEntryPoint unauthorizedEntryPoint;
    ///   jwt 拒绝访问程序
    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    public TokenWebSecurityConfig(UserDetailsServiceImpl userDetailsService, DefaultPasswordEncoder defaultPasswordEncoder,
                                  TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.userDetailsService = userDetailsService;
        this.defaultPasswordEncoder = defaultPasswordEncoder;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;

    }
    /**
     * 配置设置
     * @param http
     * @throws Exception
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                //.authenticationEntryPoint(new UnauthorizedEntryPoint())
                // 认证入口
                .authenticationEntryPoint(unauthorizedEntryPoint)
                // .accessDeniedHandler(jwtAccessDeniedHandler)
                .and().csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and().logout().logoutUrl("/userEntity/logout")
                .addLogoutHandler(new TokenLogoutHandler(tokenManager,redisTemplate)).and()
                .addFilter(new TokenLoginFilter(authenticationManager(), tokenManager, redisTemplate))
                .addFilter(new TokenAuthenticationFilter(authenticationManager(), tokenManager, redisTemplate));
                //自定义csrf防御
       // http.formLogin().loginPage("/admin/acl/login").usernameParameter("username").passwordParameter("password");

        http.cors();
        RequestMatcher requestMatcher = new CsrfSecurityRequestMatcher();
        http.csrf().requireCsrfProtectionMatcher(requestMatcher);
    }
    /**
     *  登录信息  查询权限  +  用户
     * @param auth
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
    }

    /**
     * 配置哪些请求不拦截
     * @param web
     * @throws Exception "/","/login",
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/**",
                "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"
               );
    }

    /*  解决前端跨域的问题*/
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOriginPattern("*");//修改为添加而不是设置，* 最好改为实际的需要，我这是非生产配置，所以粗暴了一点
        configuration.addAllowedMethod("*");//修改为添加而不是设置
        configuration.addAllowedHeader("*");
        //这里很重要，起码需要允许 Access-Control-Allow-Origin
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


}